// var levelOrder = function (root) {
//     let result = []
//     if (!root) return result;
//     let queue = []
//     queue.push(root)

//     while (queue.length) {
//         let level = []
//         let len = queue.length

//         for (let i = 0; i < len; i++) {
//             let top = queue.shift()
//             level.push(top.val)
//             if (top.left) {
//                 queue.push(top.left)
//             }
//             if (top.right) {
//                 queue.push(top.right)
//             }
//         }
//         result.push(level)
//     }
//     return result;
// }

var levelOrder = function (root) {
    // 二叉树的层序遍历
    // 思路：使用队列，遍历二叉树的节点，取出来时将它的子节点再存储到队列中
    let res = [];
    let queue = [];
    if (!root) return res;
    queue.push(root)

    while (queue.length) {
        let level = [];
        let len = queue.length;

        for (let i = 0; i < len; i++) {
            let top = queue.shift();
            level.push(top.val);

            if (top.left) {
                queue.push(top.left)
            }
            if (top.right) {
                queue.push(top.right)
            }
        }
        res.push(level);
    }
    return res;
}